package com.ciwong.epaper.modules.me;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Spinner;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.application.EpaperConstant;
import com.ciwong.epaper.modules.epaper.adapter.DubReCommendAdapter;
import com.ciwong.epaper.modules.epaper.adapter.DubReGradeSpinnerAdapter;
import com.ciwong.epaper.modules.epaper.adapter.DubReZjSpinnerAdapter;
import com.ciwong.epaper.modules.epaper.adapter.SearchDubVideoAdapter;
import com.ciwong.epaper.modules.epaper.bean.Grade;
import com.ciwong.epaper.modules.epaper.dao.EpaperDao;
import com.ciwong.epaper.modules.me.bean.DubHotWord;
import com.ciwong.epaper.modules.me.util.MeJumpManager;
import com.ciwong.epaper.modules.me.widget.SpaceItemDecoration;
import com.ciwong.epaper.modules.msg.bean.WorkContent;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.libs.utils.NetworkUtils;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.i.BaseQuickOnItemClickListener;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.utils.ToastUtil;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @description:搜索趣配音列表页面
 * @author: wyk
 * @time: 2022/1/17 16:50
 */
public class SearchDubActivity extends BaseActivity implements View.OnClickListener, AdapterView.OnItemClickListener {

    /**
     * 每页数据大小
     */
    private static final int LOAD_PAGE_SIZE = 49;
    /**
     * 当前页码
     */
    private int curPage = 1;

    /**
     * 搜索结果显示
     */
    private RecyclerView lv_searchResult;
    /**
     * 正在搜索中的页面
     */
    private RelativeLayout rel_searching;

    /**
     * 搜索结果为空
     */
    private RelativeLayout rel_search_empty;

    /**
     * 搜索关键字
     */
    private EditText edt_searching_book_str;
    /**
     * 搜索中的动画图片
     */
    ImageView iv_searching_book;

    ImageView iv_search_dot1;
    ImageView iv_search_dot2;
    ImageView iv_search_dot3;
    /**
     * 热门搜索词语
     */
    private ListView lv_hot_word;
    private LinearLayout ll_hot_word;
    private DubReCommendAdapter hotWordAdapter;
    private DubReZjSpinnerAdapter zjWordAdapter;
    private DubReGradeSpinnerAdapter gradeWordAdapter;
    //年级id
    private int mGradeId;

    private List<WorkContent> searchBookList = new ArrayList<WorkContent>();
    private List<DubHotWord> dubHotWords = new ArrayList<>();
    private List<Grade> gradeHotWords = new ArrayList<>();
    private List<DubHotWord> zjHotWords = new ArrayList<>();
    private SearchDubVideoAdapter mSearchDubVideoAdapter;

    private Spinner sp_grade, sp_cid;


    /**
     * 是否正在搜索，
     * 防止监听键盘时搜索两次
     */
    private boolean isSearching = false;

    /**
     * 清除搜索关键字
     */
    ImageView iv_clear_keywords;

    @Override
    protected int setView() {
        return R.layout.activity_search_dub;
    }

    @Override
    protected void findViews() {

        lv_searchResult = findViewById(R.id.swipe_target);
        rel_searching = findViewById(R.id.rel_searching);
        rel_search_empty = findViewById(R.id.rel_search_empty);
        iv_searching_book = findViewById(R.id.iv_searching_book);
        edt_searching_book_str = findViewById(R.id.edt_searching_book_str);
        edt_searching_book_str.setSingleLine();
        ll_hot_word = findViewById(R.id.ll_hot_word);
        lv_hot_word = findViewById(R.id.lv_hot_word);
        iv_search_dot1 = findViewById(R.id.iv_search_dot1);
        iv_search_dot2 = findViewById(R.id.iv_search_dot2);
        iv_search_dot3 = findViewById(R.id.iv_search_dot3);
        iv_clear_keywords = findViewById(R.id.iv_clear_keywords);

        sp_grade = findViewById(R.id.sp_grade);
        sp_cid = findViewById(R.id.sp_cid);
    }

    @Override
    protected void initEvent() {
        iv_clear_keywords.setOnClickListener(this);
        lv_hot_word.setOnItemClickListener(this);

        edt_searching_book_str.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().isEmpty()) {
                    iv_clear_keywords.setImageResource(R.mipmap.btn_search_empty);
                } else {
                    iv_clear_keywords.setImageResource(R.mipmap.btn_search_clean);
                }
            }
        });

    }

    @Override
    protected void init() {
        setTitleText(R.string.search);
//        if (EApplication.getInstance().getClazz() != null) {
//            mGradeId = EApplication.getInstance().getClazz().getGradeId();
//        }
        mGradeId = 0;
        lv_searchResult.setLayoutManager(new GridLayoutManager(SearchDubActivity.this, 2));
        lv_searchResult.addItemDecoration(new SpaceItemDecoration(SearchDubActivity.this, 10, 10, 10));
        mSearchDubVideoAdapter = new SearchDubVideoAdapter(R.layout.item_view_dub_video, searchBookList);
        lv_searchResult.setAdapter(mSearchDubVideoAdapter);
        mSearchDubVideoAdapter.setOnItemClickListener(new BaseQuickOnItemClickListener() {
            @Override
            public void avertRepeatOnClick(BaseQuickAdapter adapter, View view, int position) {
                try {
                    WorkContent workContent = searchBookList.get(position);
                    if (null != workContent) {
                        MeJumpManager.jumpToDubVideoDetailActivity(EpaperConstant.REQUEST_CODE_GET_VIDEO_MASTER_STATE, R.string.go_back,
                                SearchDubActivity.this, "", workContent, "0", 0, false);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });
    }

    @Override
    protected void loadData() {
        hotWordAdapter = new DubReCommendAdapter(dubHotWords);
        lv_hot_word.setAdapter(hotWordAdapter);

        gradeHotWords.add(new Grade(0, "全部"));
        gradeHotWords.add(new Grade(1107, "七年级"));
        gradeHotWords.add(new Grade(1108, "八年级"));
        gradeHotWords.add(new Grade(1109, "九年级"));
//        gradeHotWords.add(new Grade(-99, "其他"));

//        ArrayAdapter<Grade> adapter = new ArrayAdapter<Grade>(this,
//                R.layout.spinner_item_searchdub, gradeHotWords);
//
//        adapter.setDropDownViewResource(R.layout.spinner_dropdown_searchdub);
//        sp_grade.setAdapter(adapter);
        gradeWordAdapter = new DubReGradeSpinnerAdapter(gradeHotWords);
        sp_grade.setAdapter(gradeWordAdapter);


        sp_grade.setSelection(0);
        zjHotWords.add(new DubHotWord("", 0, "专辑"));
        zjWordAdapter = new DubReZjSpinnerAdapter(zjHotWords);
        sp_cid.setAdapter(zjWordAdapter);
        sp_cid.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (zjHotWords.size() <= 1) {
                    return;
                }
                if (position == 0) {
                    edt_searching_book_str.setText("");
                    showHotWordView();
                } else {
                    String hotWord = zjHotWords.get(position).getName();
                    edt_searching_book_str.setText(hotWord);
                    loadDataFromNet();
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        sp_grade.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                mGradeId = gradeHotWords.get(position).getGradeId();
                edt_searching_book_str.setText("");
                sp_cid.setSelection(0);
                getDubbingVideoCid();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });


        getDubVideoRecommend();
        getDubbingVideoCid();

    }

    /**
     * 显示搜索View
     */
    private void showSearchingView() {
        ll_hot_word.setVisibility(View.GONE);
        rel_search_empty.setVisibility(View.GONE);
        lv_searchResult.setVisibility(View.GONE);
        rel_searching.setVisibility(View.VISIBLE);
        startLoadingAnim();
    }

    /**
     * 根据关键字搜索配音列表
     */
    public void loadDataFromNet() {
        if (!NetworkUtils.isOnline()) {
            ToastUtil.INSTANCE.toastCenterNoNetError();
            isSearching = false;
            return;
        }
        String putKeyWords = edt_searching_book_str.getText().toString();
        final String keyWords = putKeyWords.trim();
        if (TextUtils.isEmpty(keyWords)) {
//            CWToast.makeText(this, "搜索关键字不能为空", Toast.LENGTH_SHORT, true).setToastType(CWToast.TOAST_TYPE_ERROR).show();
            isSearching = false;
            showNormalView();
            return;
        }
        String keyWord = putKeyWords;
        try {
            keyWord = URLEncoder.encode(keyWords, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        showSearchingView();
        EpaperDao.getInstance().getDubbingVideoListByName(mGradeId, keyWord, curPage, LOAD_PAGE_SIZE, new BaseExtCallBack(SearchDubActivity.this, getUserInfoBase().getUserId() + "") {
            @Override
            public void failed(Object data) {
                isSearching = false;
                showEmptyView();
            }

            @Override
            public void failed(int errorCode, Object data) {
                isSearching = false;
                showEmptyView();
            }

            @Override
            public void success(Object data) {
                isSearching = false;
                showNormalView();
                try {
                    if (data != null && data instanceof ArrayList) {
                        List<WorkContent> workContentList = (ArrayList<WorkContent>) data;
                        if (workContentList != null && workContentList.size() > 0) {
                            searchBookList = workContentList;
                            mSearchDubVideoAdapter.setNewData(searchBookList);
                        } else {
                            showEmptyView();
                        }
                    }
                } catch (Exception e) {
                    e.getStackTrace();
                }
            }
        });
    }

    /**
     * 获取搜索配音关键词
     */
    private void getDubVideoRecommend() {
        try {
            EpaperDao.getInstance().getDubbingVideoRecommend(mGradeId, new BaseCallBack() {
                @Override
                public void failed(int errorCode, Object data) {
                    showNormalView();

                }

                @Override
                public void failed(Object data) {
                    showNormalView();

                }

                @Override
                public void success(Object data) {
                    dubHotWords.clear();
                    super.success(data);
                    if (data != null) {
                        List<DubHotWord> searchBookKeyNameBean = (List<DubHotWord>) data;
                        if (searchBookKeyNameBean.size() > 0) {
                            dubHotWords.addAll(searchBookKeyNameBean);
                            showHotWordView();
                            hotWordAdapter.notifyDataSetChanged();
                        }
                    } else {
                        showNormalView();
                    }

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取目录专辑
     */
    private void getDubbingVideoCid() {
        try {
            EpaperDao.getInstance().getDubbingVideoCid(mGradeId, new BaseCallBack() {
                @Override
                public void failed(int errorCode, Object data) {
                    showNormalView();

                }

                @Override
                public void failed(Object data) {
                    showNormalView();

                }

                @Override
                public void success(Object data) {
//                    dubHotWords.clear();
                    zjHotWords.clear();
                    zjHotWords.add(new DubHotWord("", 0, "专辑"));
                    super.success(data);
                    if (data != null) {
                        List<DubHotWord> searchBookKeyNameBean = (List<DubHotWord>) data;
                        if (searchBookKeyNameBean.size() > 0) {
                            zjHotWords.addAll(searchBookKeyNameBean);
                            zjWordAdapter.notifyDataSetChanged();

                        }
                    } else {
                        showNormalView();
                    }

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 监听键盘，如果是回车，就开始搜索配音
     *
     * @param event
     * @return
     */
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
            /*隐藏软键盘*/
            InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            if (inputMethodManager.isActive()) {
                inputMethodManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
            }
            if (!isSearching) {//防止监听键盘时搜索两次
                isSearching = true;
                loadDataFromNet();
            }
            return true;
        }
        return super.dispatchKeyEvent(event);
    }

    /**
     * 开始加载动画
     */
    private void startLoadingAnim() {
        iv_search_dot1.setVisibility(View.GONE);
        iv_search_dot2.setVisibility(View.GONE);
        iv_search_dot3.setVisibility(View.GONE);
        loadingAnimHandler.removeMessages(1);
        loadingAnimHandler.removeMessages(2);
        loadingAnimHandler.removeMessages(3);
        loadingAnimHandler.removeMessages(4);
        loadingAnimHandler.sendEmptyMessageDelayed(1, 500);
        loadingAnimHandler.sendEmptyMessageDelayed(2, 1000);
        loadingAnimHandler.sendEmptyMessageDelayed(3, 1500);
        loadingAnimHandler.sendEmptyMessageDelayed(4, 2000);
    }

    private Handler loadingAnimHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    iv_search_dot1.setVisibility(View.VISIBLE);
                    break;
                case 2:
                    iv_search_dot2.setVisibility(View.VISIBLE);
                    break;
                case 3:
                    iv_search_dot3.setVisibility(View.VISIBLE);
                    break;
                case 4:
                    startLoadingAnim();
                    break;
            }
        }
    };

    /**
     * 显示搜索关键词view
     */
    public void showHotWordView() {
        ll_hot_word.setVisibility(View.VISIBLE);
        lv_hot_word.setVisibility(View.VISIBLE);
        lv_searchResult.setVisibility(View.GONE);
        rel_search_empty.setVisibility(View.GONE);
        rel_searching.setVisibility(View.GONE);

//        sp_cid.setSelection(0);
    }

    public void showNormalView() {
        ll_hot_word.setVisibility(View.GONE);
        rel_search_empty.setVisibility(View.GONE);
        rel_searching.setVisibility(View.GONE);
        lv_searchResult.setVisibility(View.VISIBLE);
        removeAnimaMessages();
    }

    public void showEmptyView() {
        ll_hot_word.setVisibility(View.GONE);
        rel_search_empty.setVisibility(View.VISIBLE);
        rel_searching.setVisibility(View.GONE);
        lv_searchResult.setVisibility(View.GONE);
        removeAnimaMessages();
    }

    private void removeAnimaMessages() {
        loadingAnimHandler.removeMessages(1);
        loadingAnimHandler.removeMessages(2);
        loadingAnimHandler.removeMessages(3);
        loadingAnimHandler.removeMessages(4);
    }


    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.iv_clear_keywords) {//清除搜索关键字
            edt_searching_book_str.setText("");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        removeAnimaMessages();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long l) {
        int viewId = parent.getId();
        if (viewId == R.id.lv_hot_word) {//点击热门搜索词
            String hotWord = dubHotWords.get(position).getName();
            edt_searching_book_str.setText(hotWord);
            loadDataFromNet();
        }
    }

}
